<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../css/public.css" media="all">
    <style>
        .label_td{
            width: 50px;
            background-color: #FBFBFB
        }
        .pane_info .layui-form-item{
            margin-bottom:0px
        }
        .pane_info .layui-form .layui-table td, .layui-table th{
            padding: 4px 4px
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">api名称</label>
                            <div class="layui-input-inline">
                                <input type="text" name="apiName" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">api地址</label>
                            <div class="layui-input-inline">
                                <input type="text" name="apiUrl" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary"  lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加 </button>
                <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete"> 删除 </button>
            </div>
        </script>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-primary layui-btn-xs " lay-event="detail">详情</a>
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>

    </div>
</div>
<!--数据操作-->
<script type="text/html" id="data_operation">
    <div class="pane_info">
        {{#  if(!d.edit){ }}
        <table class="layui-table info-pane">
            <tbody>
            <tr>
                {{#  layui.each(d.list, function(index, item){ }}
                <tr>
                    {{#  layui.each(item.model, function(i, e){ }}
                        <td colspan="{{ item.colspan }}" class="label_td">
                            {{ e.label }}
                        </td>
                        <td>
                            {{#  if(e.component ==='select'){ }}
                                {{#  layui.each(e.list, function(n, o){ }}
                                    {{#  if(o.value==e.value){ }}
                                        {{ o.label }}
                                    {{#  } }}
                                {{#  }); }}
                            {{#  }else if(e.component ==='radio'){ }}
                                {{#  layui.each(e.list, function(n, o){ }}
                                    {{#  if(o.value==e.value){ }}
                                        {{ o.label }}
                                    {{#  } }}
                                {{#  }); }}
                            {{#  }else if(e.component ==='checkbox'){ }}
                                {{#  layui.each(e.list, function(n, o){ }}
                                    {{#  if(e.valueList){ }}
                                        {{#  if(e.valueList.includes(o.value)){ }}
                                            {{ o.label }}
                                            {{#  if((e.list.length-1)!==n){ }}
                                                ,
                                            {{#  } }}
                                        {{#  } }}
                                    {{#  } }}
                                {{#  }); }}
                            {{#  }else{ }}
                                {{ e.value }}
                            {{#  } }}
                        </td>
                    {{#  }); }}
                </tr>
                {{#  }); }}
            </tr>
            </tbody>
        </table>
        {{#  }else{ }}
        <form class="layui-form layui-form-pane" action="" lay-filter="demo-lay-filter-datainfo">
            {{#  if(d.dataId){ }}
            <input type="hidden"  name="dataId" value="{{d.dataId}}" >
            {{#  } }}
            <table class="layui-table info-pane">
                <tbody>
                    {{#  layui.each(d.list, function(index, item){ }}
                        <tr>
                            {{#  layui.each(item.model, function(i, e){ }}
                                <td colspan="{{ item.colspan }}">
                                    {{#  if(e.component ==='input'){ }}
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">{{ e.label }}</label>
                                            <div class="layui-input-block">
                                                <input type="text"  name="{{ e.name }}" autocomplete="off" class="layui-input" placeholder="{{ e.placeholder}}" value="{{ e.value ? e.value : '' }}"  {{ e.required ? 'lay-verify="required"' : '' }}>
                                            </div>
                                        </div>
                                    {{#  }else if(e.component ==='date'){ }}
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">{{ e.label }}</label>
                                            <div class="layui-input-block">
                                                <input type="text" name="{{ e.name }}" id="date_{{ e.name }}" placeholder="{{ e.placeholder}}" value="{{ e.value ? e.value : '' }}"   {{ e.required ? 'lay-verify="required"' : '' }} autocomplete="off" class="layui-input">
                                            </div>
                                        </div>
                                    {{#  }else if(e.component ==='datetime'){ }}
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">{{ e.label }}</label>
                                            <div class="layui-input-block">
                                                <input type="text" name="{{ e.name }}" id="date_{{ e.name }}" placeholder="{{ e.placeholder}}" value="{{ e.value ? e.value : '' }}"   {{ e.required ? 'lay-verify="required"' : '' }} autocomplete="off" class="layui-input">
                                            </div>
                                        </div>
                                    {{#  }else if(e.component ==='textarea'){ }}
                                        <div class="layui-form-item layui-form-text">
                                            <label class="layui-form-label">{{ e.label }}</label>
                                            <div class="layui-input-block">
                                                <textarea placeholder="请输入内容" name="{{ e.name }}" class="layui-textarea"  >{{e.value ? e.value :''}}</textarea>
                                            </div>
                                        </div>
                                    {{#  }else if(e.component ==='select'){ }}
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">{{ e.label }}</label>
                                            <div class="layui-input-block">
                                                <select name="{{ e.name }}" lay-filter="{{ e.name }}" {{ e.isSearch ? 'lay-search=""' : ''}}>
                                                    <option value="">{{ e.placeholder?e.placeholder:'请选择' }}</option>
                                                    {{#  layui.each(e.list, function(n, o){ }}
                                                        {{#  if(e.value){ }}
                                                            <option value="{{o.value}}"  {{ o.value==e.value ? 'selected' : '' }} >{{ o.label}}</option>
                                                        {{#  }else{ }}
                                                            <option value="{{o.value}}">{{ o.label}}</option>
                                                        {{#  } }}
                                                    {{#  }); }}
                                                </select>
                                            </div>
                                        </div>
                                    {{#  }else if(e.component ==='radio'){ }}
                                        <div class="layui-form-item" pane="">
                                            <label class="layui-form-label">{{ e.label }}</label>
                                            <div class="layui-input-block">
                                                {{#  layui.each(e.list, function(n, o){ }}
                                                    {{#  if(e.value){ }}
                                                        <input type="radio" lay-filter="{{ e.name }}" name="{{ e.name }}" value="{{o.value }}" title="{{ o.label }}" {{ o.value == e.value ? 'checked' : '' }}>
                                                    {{#  }else{ }}
                                                        <input type="radio" lay-filter="{{ e.name }}" name="{{ e.name }}" value="{{ o.value }}" title="{{ o.label }}">
                                                    {{#  } }}
                                                {{#  }); }}
                                            </div>
                                        </div>
                                    {{#  }else if(e.component=='checkbox'){  }}
                                        <div class="layui-form-item" pane="">
                                            <label class="layui-form-label">{{ e.label }}</label>
                                            <div class="layui-input-block">
                                                {{#  layui.each(e.list, function(n, o){ }}
                                                    {{#  if(e.valueList){ }}
                                                        <input lay-skin="primary" type="checkbox" lay-filter="{{ o.value }}" name="{{ o.value }}" title="{{ o.label }}" {{ e.valueList.includes(o.value) ? 'checked' : '' }}>
                                                    {{#  }else{ }}
                                                        <input lay-skin="primary" type="checkbox" lay-filter="{{ o.value }}" name="{{ o.value }}" title="{{ o.label }}" >
                                                    {{#  } }}
                                                {{#  }); }}
                                            </div>
                                        </div>
                                    {{#  }else if(e.component=='switch'){ }}
                                        <div class="layui-form-item" pane="">
                                            <label class="layui-form-label">{{ e.label }}</label>
                                            <div class="layui-input-block">
                                                <input type="checkbox" {{e.value ? 'checked' : '' }} name="{{ e.name }}" lay-filter="{{ e.name }}" lay-skin="switch" lay-text="{{ e.labelText ? e.labelText : 'ON|OFF'}}">
                                            </div>
                                        </div>
                                    {{#  } }}
                                </td>
                            {{#  }); }}
                        </tr>
                    {{#  }); }}
                </tbody>
            </table>
        </form>
        {{#  } }}
    </div>
</script>


<script src="../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="../js/jquery-3.7.1.min.js"></script>
<script src="../js/crypto-js.min.js"></script>
<script src="../js/common.js"></script>
<script src="/lay/t-secrypt-script.js"></script>
<script>

    layui.use(['form', 'table','laytpl','laydate'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table;
        var laydate = layui.laydate;
        var laytpl = layui.laytpl; //模版

        let tableUrl="/sys-open-api/page";
        let saveOrUpdateUrl="/sys-open-api/saveorupdate";
        let deleteDataUrl="/sys-open-api/del/batch";
        let id="id";
        let name="apiName"

        let formList=[
            { model:[
                    {label:'api名称',component:'input',name:'apiName',placeholder:"请输入api名称",required:true,requiredMsg:'api名称必填',value:""},
                ],colspan:2},
            { model:[
                    {label:'api地址',component:'input',name:'apiUrl',placeholder:"请输入api地址",required:true,requiredMsg:'api接口必填',value:""},
                ],colspan:2},
            { model:[
                    {label:'api类型',component:'select',name:'apiType',placeholder:"请选择api类型",required:true,requiredMsg:'api类型必填',value:"",url:'/sys-open-api/gettype'},
                ],colspan:2},
            { model:[
                    {label:'api备注',component:'textarea',name:'apiNote',required:true,requiredMsg:'api备注必填',value:''},
                ],colspan:2},

        ]

        table.render({
            elem: '#currentTableId',
            method:'POST',
            url: tableUrl,
            toolbar: '#toolbarDemo',
            contentType:'application/json',
            request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
            },
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                {type: "checkbox", width: 50},
                {field: 'id', width: 80, title: 'ID', sort: true},
                {field: 'apiName', width: 180, title: 'api名称'},
                {field: 'apiUrl', width: 180, title: 'api地址', sort: true},
                {field: 'apiTypeName', width: 180, title: 'api类型'},
                {field: 'apiNote', width: 180, title: 'api备注'},
                {field: 'createTime', width: 180, title: '创建时间'},
                {title: '操作',fixed: 'right', minWidth: 200, toolbar: '#currentTableBar', align: "center"}
            ]],
            limits: [10, 15, 20, 25, 50, 100],
            limit: 15,
            page: true,
            skin: 'line'
        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            var result = JSON.stringify(data.field);
            //执行搜索重载
            table.reload('currentTableId', {
                page: {
                    curr: 1
                }
                , where: {
                    search: data.field
                }
            }, 'data');
            return false;
        });

        /**
         * toolbar监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                let initData={};
                initData.list=formList;
                setFormEmptyValue();
                add(initData);
            } else if (obj.event === 'delete') {  // 监听删除操作
                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                if(data.length==0){
                    return layer.msg('未选择数据', {icon: 0});
                }
                let arr=[];
                for (let i = 0; i < data.length ; i++) {
                    let o=data[i];
                    arr.push(o[id]+'');
                }
                layer.confirm('确认删除选中数据吗', function (index) {
                    layer.close(index);
                    del(arr);
                })
            }
        });

        //监听表格复选框选择
        table.on('checkbox(currentTableFilter)', function (obj) {
            console.log(obj)
        });

        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                setFormEmptyValue();
                setFormValue(data);
                data.list=formList;
                update(data);
                return false;
            } else if (obj.event === 'delete') {
                layer.confirm('确认删除【'+data[name]+'】吗', function (index) {
                    layer.close(index);
                    let arr=[];
                    arr.push(data[id]+'')
                    del(arr);
                });
            }else if(obj.event==='detail'){
                let detailObj={};
                detailObj.list=formList;
                setFormEmptyValue();
                setFormValue(data);
                detail(detailObj);
                return false;
            }
        });

        function add(data){
            data.edit=true;
            templateRender('data_operation',data,function (html){
                layerPage('添加操作',html,data,'50%','70%',function (index){
                    let json = form.val('demo-lay-filter-datainfo');
                    getFromValue(json);
                    layutils.ajaxJsonPost(saveOrUpdateUrl,JSON.stringify(json),function (res){
                        if(res.code==200){
                            layer.msg(res.message, {icon: 1},function (){
                            });
                            layer.close(index);
                            table.reload('currentTableId');
                        }else {
                            layer.msg(res.message, {icon: 2});
                        }
                    })
                })
                formRender();
            })
        }

        function detail(data){
            data.edit=false;
            templateRender('data_operation',data,function (html){
                layerDetailPage('查看详情',html,data,'50%','70%')
            })
        }

        function update(data){
            data.edit=true;
            data.dataId=data[id];
            templateRender('data_operation',data,function (html){
                layerPage('修改操作',html,data,'50%','70%',function (index){
                    let json = form.val('demo-lay-filter-datainfo');
                    json[id]=json.dataId;
                    delete json.dataId;
                    getFromValue(json);
                    layutils.ajaxJsonPost(saveOrUpdateUrl,JSON.stringify(json),function (res){
                        if(res.code==200){
                            layer.msg(res.message, {icon: 1},function (){
                            });
                            layer.close(index);
                            table.reload('currentTableId');
                        }else {
                            layer.msg(res.message, {icon: 2});
                        }
                    })
                })
                formRender();
            })
        }

        function del(ids){
            let idData={ids:ids};
            layutils.ajaxJsonPost(deleteDataUrl,JSON.stringify(idData),function (res){
                if(res.code==200){
                    layer.msg(res.message, {icon: 1});
                    table.reload('currentTableId');
                }else {
                    layer.msg(res.message, {icon: 2});
                }
            });
        }
        //监听事件
        function formChangeEvent(component,name,value){
            console.log(name+" name "+" value "+JSON.stringify(value));
        }

        //设置空值
        function setFormEmptyValue(){
            formList.forEach(function (item,index){
                item.model.forEach(function (o,i){
                    if(o.component==='checkbox'){
                        o.valueList=[];
                    }else if(o.component==='switch'){
                        o.value=false;
                    }else {
                        o.value='';
                    }
                })
            })
        }

        //优化设置值
        function setFormValue(obj){
            formList.forEach(function(item, index){
                item.model.forEach(function (o,i){
                    if(obj[o.name]){
                        if(o.component==='checkbox'){
                            o.valueList=obj[o.name];
                        }else {
                            o.value=obj[o.name];
                        }
                    }
                })
            })
        }
        //优化复选框
        function getFromValue(obj){
            formList.forEach(function(item, index){
                item.model.forEach(function (o,i){
                      if(o.component==='checkbox'){
                         obj[o.name]=o.valueList;
                      }else if(o.component==='switch'){
                          obj[o.name]=o.value;
                      }
                })
            })
            for (let key in obj) {
                if(obj[key]==='on'){
                    delete obj[key];
                }
            }
        }
        let cacheMap={};
        //模板渲染
        function templateRender(templateId,data,callback){
            var getTpl = $('#'+templateId).html();
            if(data.list){
                data.list.forEach(function(item, index) {
                    item.model.forEach(function (e,i) {
                        if (e.component === 'select') {
                            e.list=layutils.addKeyIfNotExists(cacheMap,e.url,function (key){
                                let data = layutils.ajaxGetAwait(e.url, null);
                                return data.data;
                            })
                            form.on('select(' + e.name + ')', function (data) {
                                e.value=data.value;
                                formChangeEvent('select', e.name, data.value);
                            })
                        } else if(e.component==='switch'){
                            form.on('switch('+e.name+')', function(data){
                                e.value=data.elem.checked;
                                formChangeEvent('switch',e.name,data.elem.checked);
                            });
                        } else if(e.component==='radio'){
                            e.list=layutils.addKeyIfNotExists(cacheMap,e.url,function (key){
                                let data = layutils.ajaxGetAwait(e.url, null);
                                return data.data;
                            })
                            // 监听单选按钮的改变事件
                            form.on('radio('+e.name+')', function(data){
                                e.value=data.value;
                                formChangeEvent('radio',e.name,data.value);
                            });
                        }else if(e.component==='checkbox'){
                            e.list=layutils.addKeyIfNotExists(cacheMap,e.url,function (key){
                                let data = layutils.ajaxGetAwait(e.url, null);
                                return data.data;
                            })
                            e.list.forEach(function (m,n){
                                form.on('checkbox('+m.value+')', function(data){
                                    if(data.elem.checked){
                                        const index = e.valueList.indexOf(m.value);
                                        if (index === -1) {
                                            e.valueList.push(m.value);
                                        }
                                    }else {
                                        const index = e.valueList.indexOf(m.value);
                                        if (index !== -1) {
                                            e.valueList.splice(index, 1); // 从索引位置移除 1 个元素
                                        }
                                    }
                                    formChangeEvent('checkbox',e.name,e.valueList);
                                })
                            })
                        }
                    })
                })
            }
            laytpl(getTpl).render(data, function(html){
                callback(html);
            });
        }

        function formRender(){
            form.render();
            formList.forEach(function(item, index){
                item.model.forEach(function (o,i){
                    if(o.component==='input'){
                        $('input[name="'+o.name+'"]').on('change', function() {
                            o.value=this.value;
                            formChangeEvent('input',o.name,this.value);
                        });
                    }else if(o.component==='textarea'){
                        $('textarea[name="'+o.name+'"]').on('change', function() {
                            o.value=this.value;
                            formChangeEvent('textarea',o.name,this.value);
                        });
                    }else if(o.component==='date'){
                        laydate.render({
                            elem: '#date_'+o.name,
                            done:function(value, date, endDate){
                                o.value=value;
                                formChangeEvent('date',o.name,value);
                            }
                        });
                    }else if(o.component==='datetime'){
                        laydate.render({
                            elem: '#date_'+o.name,
                            type:'datetime',
                            done:function(value, date, endDate){
                                o.value=value;
                                formChangeEvent('date',o.name,value);
                            }
                        });
                    }
                })
            })
        }


        function layerDetailPage(title,html,data,width,height){
            let index=layer.open({
                type: 1
                ,title: title
                ,maxmin:true
                ,area: [width, height]
                ,content: html
                ,yes: function(){
                    callback(index);
                }
                ,btn2: function(){
                    layer.close(index);
                }
            });
            return index;
        }

        //操作弹窗，充满整页
        function layerFullPage(title,html,data,callback){
            let index=layer.open({
                type: 1
                ,title: title
                ,shade: 0.2,
                maxmin:true,
                shadeClose: true,
                area: ['100%', '100%']
                ,content: html
                ,btn: ['确认', '取消']
                ,yes: function(){
                    callback(index);
                }
                ,btn2: function(){
                    layer.close(index);
                }
            });
        }

        //操作弹窗
        function layerPage(title,html,data,width,height,callback){
            let index=layer.open({
                type: 1
                ,title: title
                ,maxmin:true
                ,area: [width, height]
                ,content: html
                ,btn: ['确认', '取消']
                ,yes: function(){
                    callback(index);
                }
                ,btn2: function(){
                    layer.close(index);
                }
            });
        }

        function addClickById(id,callback){
            let id_='#'+id;
            $(id_).click(function (e){
                callback(e);
            });
        }
        //操作弹窗，充满整页
        function layerFullPage(title,html,data,callback){
            let index=layer.open({
                type: 1
                ,title: title
                ,shade: 0.2,
                maxmin:true,
                shadeClose: true,
                area: ['100%', '100%']
                ,content: html
                ,btn: ['确认', '取消']
                ,yes: function(){
                    callback(index);
                }
                ,btn2: function(){
                    layer.close(index);
                }
            });
        }
    });
</script>
</body>
</html>